<template>
  <div>
    <!-- shadow漂浮 -->
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <!-- 具名插槽全写法 -->
      <template v-slot:header>
        <!-- 添加按钮 -->
        <el-button type="primary" icon="ele-Plus" @click="showAddDialog">添加</el-button>
      </template>
      <!-- card-body -->
      <!-- table表格 -->
      <!-- border边框 stripe斑马线 data后期表格要展示的数据：数据格式必须是对象的数组 -->
      <el-table :data="trademarkList" border stripe style="margin-bottom: 20px;">
        <el-table-column label="序号" width="80" align="center" type="index">
        </el-table-column>
        <el-table-column label="品牌名称" prop="tmName"></el-table-column>
        <el-table-column label="品牌LOGO">
          <template v-slot="{row,$index}">
            <el-image :src="row.logoUrl" style="width: 100px;height: 60px">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{row,$index}">
            <el-button type="warning" size="small" icon="ele-Edit" @click="showUpdateDialog(row)">修改
            </el-button>
            <el-button type="danger" size="small" icon="ele-Delete" @click="deleteTrademark(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页器pagination  -->
      <!-- <el-pagination></el-pagination>这个是element-ui需要的是element-plus，去官网 -->
      <el-pagination v-model:current-page="page" v-model:page-size="limit" :page-sizes="[3, 5, 7, 10]"
        layout="  prev, pager, next, jumper,->,sizes,total" :total="total" @size-change="handleSizeChange"
        @current-change="getTrademarkList">
      </el-pagination>
      <!--添加和修改弹出的对话框dialog  -->
      <el-dialog v-model="isShowDialog" :title="tmForm.id ? '修改品牌' : '添加品牌'">
        <!-- 自定义内容 -->
        <el-form style="width: 80%" :rules="tmRules" ref="tmFormRef" :model="tmForm">
          <!-- <el-form-item label="Activity name" prop="name">
      <el-input v-model="ruleForm.name" />
    </el-form-item> -->
          <el-form-item label="品牌名称" label-width="100px" prop="tmName">
            <el-input v-model="tmForm.tmName" autocomplete="off" />
          </el-form-item>
          <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
            <!-- 用户头像 -->
            <el-upload class="avatar-uploader" action="/app-dev/admin/product/fileUpload" :show-file-list="false"
              :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
              <img v-if="tmForm.logoUrl" :src="tmForm.logoUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
              <template #tip>
                <div class="el-upload__tip">
                  上传的图片必须是jpg且不能大于2M
                </div>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="isShowDialog = false">取消</el-button>
            <el-button type="primary" @click="addOrUpdateTrademark">
              确定
            </el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script  lang="ts">
import { defineComponent } from "vue";
export default defineComponent({
  name: "Trademark",
});
</script>

<script lang="ts" setup>
import { ref, onMounted, reactive } from "vue";
import type { TrademarkData } from "@/api/trademark";
import trademarkApi from "@/api/trademark";
import { ElMessage,ElMessageBox } from "element-plus";
import type { UploadProps, FormRules } from "element-plus";
import { Plus } from "@element-plus/icons-vue";

// dialog相关
//添加逻辑 收集接口文档里的数据参数
const tmForm = ref<TrademarkData>({
  logoUrl: "",
  tmName: "",
});
// 获取整个el-form的组件对象
// ref如果用在html元素就是原生dom对象
// ref如果用在组件标签上就是拿组件对象
const tmFormRef = ref();

//点击添加显示dialog
const isShowDialog = ref(false);
//点击添加按钮弹出对话框dialog
const showAddDialog = () => {
  isShowDialog.value = true;
  //解决添加收集完成取消数据还在的问题
  tmForm.value = {
    tmName: "",
    logoUrl: "",
  };
  //重置校验规则使用resetFields方法
  tmFormRef.value.resetFields();
};

//点击修改按钮弹出dialog
const showUpdateDialog = (row: TrademarkData) => {
  isShowDialog.value = true;
  //重置校验规则使用resetFields方法
  tmFormRef.value.resetFields();
};
//点击确定添加或是修改品牌逻辑
const addOrUpdateTrademark = () => {
  tmFormRef.value.validate(async (isValid: boolean) => {
    if (isValid) {
      //获取数据
      let trademark = tmForm.value;
      //数据是否符合要求，符合不需要整理，不符合整理好
      try {
        await trademarkApi.addOrUpdate(trademark);
        //成功
        ElMessage.success(trademark.id ? "修改品牌成功" : "添加品牌成功");
        isShowDialog.value = false;
        getTrademarkList(trademark.id ? page.value : 1);
      } catch (error) {
        //失败
        ElMessage.error(trademark.id ? "修改品牌失败" : "添加品牌失败");
      }
    }
  });
};
// -----------------------------
// pagination相关
const page = ref(1);
const limit = ref(3);
const total = ref(0);
const trademarkList = ref<TrademarkData[]>([]);

//请求获取分页列表
const getTrademarkList = async (pager = 1) => {
  page.value = pager;
  try {
    const result = await trademarkApi.getPageList(page.value, limit.value);
    trademarkList.value = result.records;
    total.value = result.total;
    return "ok";
  } catch (error) {
    ElMessage.error("获取分页列表失败");
    return Promise.reject(error);
  }
};
onMounted(() => {
  getTrademarkList();
});

//点击切换每页数量，重新发送请求
const handleSizeChange = (size: number) => {
  limit.value = size;
  getTrademarkList();
};
// ------------------------------
//添加数
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  tmForm.value.logoUrl = response.data;
};

//对上传数据进行大小校验
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (rawFile.type !== "image/jpeg") {
    ElMessage.error("上传图片必须是jpeg/jpg文件");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("上传图片大小不得超过2MB");
    return false;
  }
  return true;
};
// -------------------------------------------------
// 自定义的验证规则函数
const validateTmName = (rule: any, value: any, callback: any) => {
  // rule 代表规则对象本身 为了占位，在此无意义
  // value 代表校验的属性值
  // callback 它是一个函数,如果这个函数写了参数,代表验证失败,传递参数是错误消息
  // 如果这个函数没有些参数,那么代表验证成功  callback性质与守卫里的next()类似
  if (value.length < 2 || value.length > 10) {
    callback(new Error("品牌名称的长度必须2-10"));
  } else {
    callback();
  }
};
//表单校验规则
const tmRules = reactive<any>({
  tmName: [
    { required: true, message: "品牌名称不能为空", trigger: "blur" },
    //表单校验
    // { min: 2, max: 10, message: "品牌名称长度需要2-10", trigger: "change" },
    //自定义校验
    { validator: validateTmName, trigger: "change" },
    ],
    logoUrl: [
    { required: true, message: "品牌logo不能为空", trigger: "change" },
  ],
});
// ------------------------------------------------------------
//点击删除品牌当前行
const deleteTrademark=(row:TrademarkData)=>{
  ElMessageBox.confirm(`您确定要删除${row.tmName}吗？`,'Warning',{
    confirmButtonText:'确定',
    cancelButtonClass:'取消',
    type:'warning',
  }).then(async()=>{
    try {
      await trademarkApi.delete(row.id as number);
      ElMessage.success({duration:3000,message:'删除品牌成功'})
      getTrademarkList(trademarkList.value.length>1?page.value:page.value-1)
    } catch (error) {
      // 如果从库当中查找不到定义的ts类型,那么就考虑原生js有没有这个数据的类/构造函数
      // 本身类和构造函数也可以作为数据类型去使用
      // return Promise.reject(new Error('哈哈哈'))
      ElMessage.error('删除品牌失败'+(error as Error).message)
    }
  })
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>